import 'package:flutter/material.dart';
import 'package:flutter_module/beans/data_layer_bean.dart';
import 'package:flutter_module/beans/data_layer_item_bean.dart';
import 'package:flutter_module/beans/project_bean.dart';
import 'package:flutter_module/map/ni_types.dart';
import 'package:flutter_module/system/functions.dart';
import 'package:flutter_module/viewModels/layer_edit_viewmodel.dart';
import 'package:flutter_module/views/fragments/layer_item_edit_fragment.dart';
import 'package:flutter_module/views/fragments/project_list_fragment.dart';
import 'package:flutter_module/views/fragments/style_setting_fragment.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

import '../fragments/layer_item_type_list_fragment.dart';

///图层创建页面
class LayerSettingFragment extends StatelessWidget {

  ///是否初始话provider
  final bool bInitProvider;

  const LayerSettingFragment(
      {this.bInitProvider = true, Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (bInitProvider) {
      return MultiProvider(
        providers: [
          ChangeNotifierProvider<LayerEditViewModel>(
              create: (_) => LayerEditViewModel()),
        ],

        ///由于路由跳转，provider 要包裹 MaterialApp ，跳转的页面才能共享viewmodel
        child: MaterialApp(home: _ProviderView(
          callBack: () {
            Navigator.pop(context);
          },
        )),
      );
    } else {
      return _ProviderView(callBack: () {
        Navigator.pop(context);
      });
    }
  }
}

class _ProviderView extends StatefulWidget {
  final PopCallBack callBack;

  const _ProviderView({required this.callBack, Key? key}) : super(key: key);

  @override
  State<_ProviderView> createState() => _ProviderViewState();
}

class _ProviderViewState extends State<_ProviderView>
    with SingleTickerProviderStateMixin {
  final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
  late final LayerEditViewModel _read =
      Provider.of<LayerEditViewModel>(context, listen: false);
  late final NavigatorState _navi = Navigator.of(context);

  late final TextEditingController _nameController;

  @override
  void initState() {
    _nameController = TextEditingController()
      ..addListener(() {
        _read.curLayer.layerName = _nameController.text;
      });
    _nameController.text = _read.curLayer.layerName;
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    _nameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey,
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        leading: BackButton(
          onPressed: () {
            widget.callBack.call();
          },
        ),
        actions: [
          TextButton(
            onPressed: () {
              if (_read.curSelectProject == null) {
                Fluttertoast.showToast(msg: "还没有选择项目");
              } else {
                _read.saveLayer().then((value) {
                  if (value == true) {
                    widget.callBack.call();
                  }
                });
              }
            },
            child: const Text(
              '创建',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: 6,
              itemBuilder: (context, index) {
                switch (index) {
                  case 0:
                    return Card(
                      child: Selector<LayerEditViewModel, Project?>(
                        selector: (context, model) => model.curSelectProject,
                        builder: (context, project, child) {
                          return ListTile(
                            leading: const Icon(Icons.folder),
                            trailing:
                                const Icon(Icons.arrow_forward_ios_outlined),
                            title: Text(project == null ? "" : project.name),
                            subtitle: Text(project == null
                                ? "新建或选择已有项目"
                                : project.describe),
                            onTap: () {
                              _read.getProjectList().then((value) {
                                _navi
                                    .push(MaterialPageRoute(builder: (context) {
                                  return const ProjectListFragment();
                                }));
                              });
                            },
                          );
                        },
                      ),
                    );
                  case 1:
                    return TextField(
                      controller: _nameController,
                      decoration: InputDecoration(
                        labelText: '图层名称: ',
                        hintText: "请输入图层名称",
                        labelStyle: const TextStyle(color: Colors.red),
                        icon: const Icon(Icons.insert_drive_file),
                        suffixIcon: IconButton(
                          tooltip: '清空',
                          icon: const Icon(Icons.clear),
                          onPressed: () {
                            _nameController.text = "";
                          },
                        ),
                      ),
                    );
                  case 2:
                    return const Text("数据类型");
                  case 3:
                    return Row(
                      children: [
                        Expanded(
                          child: Selector<LayerEditViewModel, GeometryType>(
                            selector: (context, provider) =>
                                provider.curLayer.geometryType,
                            builder: (context, value, child) {
                              return RadioListTile(
                                title: child ?? const Text("点类型"),
                                value: GeometryType.geometryTypePoint,
                                groupValue: value,
                                onChanged: (value) {
                                  _read.setLayerGeometryType(value);
                                },
                              );
                            },
                            child: const Text("点类型"),
                          ),
                        ),
                        Expanded(
                          child: Selector<LayerEditViewModel, GeometryType>(
                            selector: (context, provider) =>
                                provider.curLayer.geometryType,
                            builder: (context, value, child) {
                              return RadioListTile(
                                title: child ?? const Text("线类型"),
                                value: GeometryType.geometryTypeLine,
                                groupValue: value,
                                onChanged: (value) {
                                  _read.setLayerGeometryType(value);
                                },
                              );
                            },
                            child: const Text("线类型"),
                          ),
                        ),
                        Expanded(
                          child: Selector<LayerEditViewModel, GeometryType>(
                            selector: (context, provider) =>
                                provider.curLayer.geometryType,
                            builder: (context, value, child) {
                              return RadioListTile(
                                title: child ?? const Text("面类型"),
                                value: GeometryType.geometryTypePolygon,
                                groupValue: value,
                                onChanged: (value) {
                                  _read.setLayerGeometryType(value);
                                },
                              );
                            },
                            child: const Text("面类型"),
                          ),
                        )
                      ],
                    );
                  case 4:
                    return const Text("自定义属性");
                  case 5:
                    return AnimatedList(
                      shrinkWrap: true,
                      //为true可以解决子控件必须设置高度的问题
                      physics: const NeverScrollableScrollPhysics(),
                      //禁用滑动事件
                      key: _listKey,
                      initialItemCount: _read.curLayer.itemList.length,
                      itemBuilder: (BuildContext context, int index,
                          Animation<double> animation) {
                        return _createItemWidget(
                            index, _read.curLayer.itemList[index], animation);
                      },
                    );
                  default:
                    return Container();
                }
              },
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () {
                  _read.initLayerItem();
                  _navi.push(MaterialPageRoute(builder: (BuildContext context) {
                    return const DataLayerItemEditFragment();
                  })).then((value) {
                    if (value == "addItem") {
                      _listKey.currentState
                          ?.insertItem(_read.curLayer.itemList.length - 1);
                    }
                  });
                  // _showModalBottomSheet();
                },
                child: const Text("增加属性"),
              ),
              ElevatedButton(
                onPressed: () {
                  _navi.push(
                    MaterialPageRoute(builder: (BuildContext context) {
                      return const StyleSettingFragment();
                    }),
                  );
                  // _showModalBottomSheet();
                },
                child: const Text("渲染配置"),
              ),
            ],
          ),
        ],
      ),
    );
  }

  ///图层属性
  Widget _createItemWidget(
      final int index, final DataLayerItem item, Animation<double> animation) {
    Widget childWidget;
    switch (item.type) {
      case DataLayerItemType.dataLayerItemTypeInput:
        childWidget = ListTile(
          minVerticalPadding: 0,
          leading: LayerItemConstant.getTypeIcon(
              DataLayerItemType.dataLayerItemTypeInput),
          title: Text(
            item.nullable ? item.title : "*${item.title}",
            textAlign: TextAlign.left,
            style: TextStyle(
              color: item.nullable ? Colors.black : Colors.red,
            ),
          ),
          subtitle: Text(item.describe ?? ""),
          trailing:
              item.isMainName ? const Icon(Icons.add_location_outlined) : null,
        );
        break;
      case DataLayerItemType.dataLayerItemTypeSingleSelection:
        childWidget = ListTile(
          minVerticalPadding: 0,
          leading: LayerItemConstant.getTypeIcon(
              DataLayerItemType.dataLayerItemTypeSingleSelection),
          title: Text(
            item.nullable ? item.title : "*${item.title}",
            textAlign: TextAlign.left,
            style: TextStyle(
              color: item.nullable ? Colors.black : Colors.red,
            ),
          ),
          subtitle: Text(item.describe ?? ""),
          trailing:
              item.isMainName ? const Icon(Icons.add_location_outlined) : null,
        );
        break;
      default:
        childWidget = Container();
        break;
    }

    return ScaleTransition(
      scale: animation,
      child: Card(
          child: Row(mainAxisSize: MainAxisSize.max, children: [
        Expanded(child: childWidget),

        ///属性重新编辑按钮
        ElevatedButton(
            onPressed: () {
              _navi.push(MaterialPageRoute(builder: (context) {
                return DataLayerItemEditFragment(item: item);
              }));
            },
            child: const Icon(Icons.mode_edit_outline_outlined)),
        ElevatedButton(
            onPressed: () {
              DataLayerItem item = _read.curLayer.itemList[index];
              _listKey.currentState?.removeItem(
                  index,
                  (context, animation) =>
                      _createItemWidget(index, item, animation));
              _read.curLayer.itemList.remove(item);
            },
            child: const Icon(Icons.delete_forever)),
      ])),
    );
  }

  Widget _removeItemBuild(Widget widget, Animation<double> animation) {
    return ScaleTransition(
      scale: animation,
      child: widget,
    );
  }

// _showModalBottomSheet() {
//   showModalBottomSheet(
//     context: context,
//     builder: (context) {
//       return Column(
//         children: [
//           TextField(
//             decoration: InputDecoration(
//               labelText: '属性标题: ',
//               hintText: "请输入属性标题",
//               labelStyle: const TextStyle(color: Colors.red),
//               icon: const Icon(Icons.insert_drive_file),
//               suffixIcon: IconButton(
//                 tooltip: '清空',
//                 icon: const Icon(Icons.clear),
//                 onPressed: () {},
//               ),
//             ),
//           ),
//           PopupMenuButton<DataLayerItemType>(itemBuilder: (context) {
//             return <PopupMenuEntry<DataLayerItemType>>[
//               const PopupMenuItem<DataLayerItemType>(
//                 value: DataLayerItemType.dataLayerItemTypeInput,
//                 child: Text("data"),
//               ),
//             ];
//           })
//         ],
//       );
//     },
//     isScrollControlled: true,
//     isDismissible: false,
//   );
// }
}
